
#include <stdio.h>
#include <stdlib.h>
#include "bin_tree.h"

static void print(Key key) {
    printf("%d, ", key);
}

static void report_tree(BinTree * tree) {
    printf("tree size: %d\n", tree->size);
    if (IsEmpty(tree)) {
        printf("tree is empty!\n");
        return;
    }
    
    printf("show inorder:\n");
    TreeInorderWalk(tree, print);
    putchar('\n');

    BTNode * min = TreeMinimum(tree);
    BTNode * max = TreeMaximum(tree);
    
    printf("Minimum: %d, %p\n", min->key, min);
    printf("Maximum: %d, %p\n", max->key, max);
}

static void report_location(BinTree * tree, Key key) {
    BTNode * _node = TreeSearch(tree, key);
    if (_node == NULL) {
        printf("key(%d) is not found.\n", key);
        return;
    }
    
    printf("Search key(%d): %d, %p\n", key, _node->key, _node);

    BTNode * pred = TreePredecessor(_node);
    if (pred == NULL) {
        printf("key(%d) have no predecessor.\n", key);
    } else {
        printf("Predecessor of %d: %d, %p\n", key, pred->key, pred);
    }
    
    BTNode * succ = TreeSuccessor(_node);
    if (succ == NULL) {
        printf("key(%d) have no successor.\n", key);
    } else {
        printf("Successor of %d: %d, %p\n", key, succ->key, succ);
    }
    
}


int a[20] = {35, 11, 26, 56, 27, 65, 36, 50, 49, 99, 62, 13, 72, 77, 83, 16, 86, 20, 42, 73};

int main(void) {

    BinTree tree;
    TreeInitialized(&tree);

    printf("---------------------------------- Init:\n");
    report_tree(&tree);
    
    Key key;
    for(int i = 0; i < 20; i++)
    {
        key = a[i];
        TreeInsert(&tree, key);
    }

    printf("---------------------------------- Builded:\n");
    report_tree(&tree);
    report_location(&tree, 11);
    report_location(&tree, 99);
    report_location(&tree, 62);

    printf("---------------------------------- Delete key 65:\n");
    BTNode * node_to_delete = TreeSearch(&tree, 65);
    if (node_to_delete != NULL) {
        TreeDelete(&tree, node_to_delete);
        report_tree(&tree);
        report_location(&tree, 62);
    }
    
    TreeRelease(&tree);
}

int KeyCompare(Key k1, Key k2) {
    if (k1 == k2) {
        return 0;
    } else if (k1 > k2) {
        return 1;
    } else {
        return -1;
    }
    
}